package com.zb.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjCustomerWxAuthor;
import com.zb.mapper.ZjCustomerWxAuthorMapper;
import com.zb.service.ZjCustomerWxAuthorService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 商家微信授权认证表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-03-01
 */
@Service
public class ZjCustomerWxAuthorServiceImpl extends ServiceImpl<ZjCustomerWxAuthorMapper, ZjCustomerWxAuthor> implements ZjCustomerWxAuthorService {
    @Resource
    private ZjCustomerWxAuthorMapper customerWxAuthorMapper;

    // 保存或更新商家认证微信
    @Override
    public void save(Long custAccId, String authorizerAppid, String authorizerRefreshToken, String openAppid) {
        ZjCustomerWxAuthor wxAuthor = this.getById(custAccId);
        if (null != wxAuthor) {
            ZjCustomerWxAuthor updateWxAuthor = new ZjCustomerWxAuthor();
            updateWxAuthor.setId(custAccId);
            updateWxAuthor.setAuthor(true);
            updateWxAuthor.setAuthorizerAppid(authorizerAppid);
            updateWxAuthor.setAuthorizerRefreshToken(authorizerRefreshToken);
            updateWxAuthor.setOpenAppid(openAppid);
            this.updateById(updateWxAuthor);
            return;
        }
        wxAuthor = new ZjCustomerWxAuthor();
        wxAuthor.setId(custAccId);
        wxAuthor.setAuthor(true);
        wxAuthor.setAuthorizerAppid(authorizerAppid);
        wxAuthor.setAuthorizerRefreshToken(authorizerRefreshToken);
        wxAuthor.setOpenAppid(openAppid);
        this.save(wxAuthor);
    }

    // 根据商家ID获取微信授权信息
    @Override
    public ZjCustomerWxAuthor getAuthorizerById(Long custAccId) {
        return customerWxAuthorMapper.getAuthorizerById(custAccId);
    }

    // 获取商家微信授权信息
    @Override
    public Object getCustomerWxAuthor(Long custAccId) {
        Map<String, Object> resultMap = new HashMap<>();
        ZjCustomerWxAuthor wxAuthor = this.getAuthorizerById(custAccId);
        resultMap.put("author", null != wxAuthor && wxAuthor.getAuthor());
        return resultMap;
    }

    // 保存商家取消微信授权
    @Override
    public void updateCancelAuthorById(Long custAccId) {
        ZjCustomerWxAuthor wxAuthor = new ZjCustomerWxAuthor();
        wxAuthor.setId(custAccId);
        wxAuthor.setAuthor(false);
        wxAuthor.setAuthorizerAppid("");
        wxAuthor.setAuthorizerRefreshToken("");
        wxAuthor.setOpenAppid("");
        this.updateById(wxAuthor);
    }
}
